<template>
  <view class="my-coupons">
    <!-- 标签页 -->
    <view class="tabs">
      <view
        class="tab-item"
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: currentTab === index }"
        @tap="switchTab(index)"
      >
        <text>{{ tab.name }}</text>
      </view>
    </view>

    <!-- 优惠券列表 -->
    <swiper
      class="coupon-swiper"
      :current="currentTab"
      @change="handleSwiperChange"
    >
      <!-- 未使用 -->
      <swiper-item>
        <scroll-view
          scroll-y
          class="coupon-scroll"
          @scrolltolower="loadMoreUnused"
          refresher-enabled
          :refresher-triggered="unusedRefreshing"
          @refresherrefresh="onUnusedRefresh"
        >
          <view class="coupon-list">
            <view
              class="coupon-item"
              v-for="(coupon, index) in unusedCoupons"
              :key="index"
              @tap="viewCouponDetail(coupon)"
            >
              <view
                class="coupon-left"
                :class="{
                  'discount-coupon': coupon.tag === '折扣券',
                  'free-coupon': coupon.goodsType === 2
                }"
              >
                <view class="coupon-tag" v-if="coupon.goodsType !== undefined">
                  {{
                    coupon.goodsType === 0
                      ? '全场通用'
                      : coupon.goodsType === 2
                      ? '指定商品'
                      : ''
                  }}
                </view>
                <view class="discount">
                  <text class="amount">{{
                    formatAmount(coupon.discount)
                  }}</text>
                  <text class="unit">元</text>
                </view>
                <view class="condition" v-if="coupon.min > 0"
                  >满{{ formatAmount(coupon.min) }}元可用</view
                >
                <view class="condition" v-else>无门槛使用</view>
              </view>
              <view class="coupon-right">
                <view class="coupon-info">
                  <view class="coupon-name">{{ coupon.name }}</view>
                  <view class="coupon-desc">{{ coupon.desc }}</view>
                  <view class="coupon-time" v-if="!coupon.days"
                    >{{ formatDate(coupon.startTime) }} -
                    {{ formatDate(coupon.endTime) }}</view
                  >
                  <view class="coupon-time" v-else>
                    有效期：{{ coupon.days }}天
                  </view>
                </view>
                <view class="coupon-action">
                  <button class="use-btn" @tap.stop="useCoupon(coupon)">
                    去使用
                  </button>
                </view>
              </view>
            </view>

            <!-- 无优惠券提示 -->
            <view class="empty-tip" v-if="unusedCoupons.length === 0">
              <image
                class="empty-icon"
                src="/static/images/common/empty.png"
              ></image>
              <view class="empty-text">暂无可用优惠券</view>
              <button class="go-center-btn" @tap="goToCouponCenter">
                去领券中心
              </button>
            </view>

            <!-- 加载更多提示 -->
            <view class="loading-more" v-if="unusedCoupons.length > 0">
              <text v-if="unusedHasMore && !unusedLoading">上拉加载更多</text>
              <text v-else-if="unusedLoading">加载中...</text>
              <text v-else>没有更多了</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>

      <!-- 已使用 -->
      <swiper-item>
        <scroll-view
          scroll-y
          class="coupon-scroll"
          @scrolltolower="loadMoreUsed"
          refresher-enabled
          :refresher-triggered="usedRefreshing"
          @refresherrefresh="onUsedRefresh"
        >
          <view class="coupon-list">
            <view
              class="coupon-item used"
              v-for="(coupon, index) in usedCoupons"
              :key="index"
              @tap="viewCouponDetail(coupon)"
            >
              <view
                class="coupon-left"
                :class="{
                  'discount-coupon': coupon.tag === '折扣券',
                  'free-coupon': coupon.tag === '免费券'
                }"
              >
                <view class="discount">
                  <text class="amount">{{
                    formatAmount(coupon.discount)
                  }}</text>
                  <text class="unit">元</text>
                </view>
                <view class="condition" v-if="coupon.min > 0"
                  >满{{ formatAmount(coupon.min) }}元可用</view
                >
                <view class="condition" v-else>无门槛使用</view>
              </view>
              <view class="coupon-right">
                <view class="coupon-info">
                  <view class="coupon-name">{{ coupon.name }}</view>
                  <view class="coupon-desc">{{ coupon.desc }}</view>
                  <view class="coupon-time" v-if="!coupon.days"
                    >{{ formatDate(coupon.startTime) }} -
                    {{ formatDate(coupon.endTime) }}</view
                  >
                  <view class="coupon-time" v-else>
                    有效期：{{ coupon.days }}天
                  </view>
                </view>
                <view class="status-mark">已使用</view>
              </view>
            </view>

            <!-- 无优惠券提示 -->
            <view class="empty-tip" v-if="usedCoupons.length === 0">
              <image
                class="empty-icon"
                src="/static/images/common/empty.png"
              ></image>
              <view class="empty-text">暂无已使用的优惠券</view>
            </view>

            <!-- 加载更多提示 -->
            <view class="loading-more" v-if="usedCoupons.length > 0">
              <text v-if="usedHasMore && !usedLoading">上拉加载更多</text>
              <text v-else-if="usedLoading">加载中...</text>
              <text v-else>没有更多了</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>

      <!-- 已过期 -->
      <swiper-item>
        <scroll-view
          scroll-y
          class="coupon-scroll"
          @scrolltolower="loadMoreExpired"
          refresher-enabled
          :refresher-triggered="expiredRefreshing"
          @refresherrefresh="onExpiredRefresh"
        >
          <view class="coupon-list">
            <view
              class="coupon-item expired"
              v-for="(coupon, index) in expiredCoupons"
              :key="index"
              @tap="viewCouponDetail(coupon)"
            >
              <view
                class="coupon-left"
                :class="{
                  'discount-coupon': coupon.tag === '折扣券',
                  'free-coupon': coupon.tag === '免费券'
                }"
              >
                <view class="discount">
                  <text class="amount">{{
                    formatAmount(coupon.discount)
                  }}</text>
                  <text class="unit">元</text>
                </view>
                <view class="condition" v-if="coupon.min > 0"
                  >满{{ formatAmount(coupon.min) }}元可用</view
                >
                <view class="condition" v-else>无门槛使用</view>
              </view>
              <view class="coupon-right">
                <view class="coupon-info">
                  <view class="coupon-name">{{ coupon.name }}</view>
                  <view class="coupon-desc">{{ coupon.desc }}</view>
                  <view class="coupon-time" v-if="!coupon.days"
                    >{{ formatDate(coupon.startTime) }} -
                    {{ formatDate(coupon.endTime) }}</view
                  >
                  <view class="coupon-time" v-else>
                    有效期：{{ coupon.days }}天
                  </view>
                </view>
                <view class="status-mark">已过期</view>
              </view>
            </view>

            <!-- 无优惠券提示 -->
            <view class="empty-tip" v-if="expiredCoupons.length === 0">
              <image
                class="empty-icon"
                src="/static/images/common/empty.png"
              ></image>
              <view class="empty-text">暂无已过期的优惠券</view>
            </view>

            <!-- 加载更多提示 -->
            <view class="loading-more" v-if="expiredCoupons.length > 0">
              <text v-if="expiredHasMore && !expiredLoading">上拉加载更多</text>
              <text v-else-if="expiredLoading">加载中...</text>
              <text v-else>没有更多了</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentTab: 0,
      unusedCoupons: [],
      usedCoupons: [],
      expiredCoupons: [],
      loading: false,
      // 分页相关
      unusedPage: 1,
      usedPage: 1,
      expiredPage: 1,
      limit: 10,
      unusedHasMore: true,
      usedHasMore: true,
      expiredHasMore: true,
      unusedLoading: false,
      usedLoading: false,
      expiredLoading: false,
      // 下拉刷新状态
      unusedRefreshing: false,
      usedRefreshing: false,
      expiredRefreshing: false
    }
  },
  computed: {
    tabs() {
      return [{ name: '未使用' }, { name: '已使用' }, { name: '已过期' }]
    },
    totalCount() {
      return (
        this.unusedCoupons.length +
        this.usedCoupons.length +
        this.expiredCoupons.length
      )
    }
  },
  onLoad() {
    // 只加载当前选中标签页的数据
    this.loadCurrentTabData()
  },
  // 页面触底事件处理函数
  onReachBottom() {
    // 在使用scroll-view的情况下，页面的onReachBottom不会被触发
    // 我们使用scroll-view的scrolltolower事件来实现触底加载
    // 此方法保留但不执行任何操作
  },
  methods: {
    // 下拉刷新处理函数 - 未使用优惠券
    onUnusedRefresh() {
      this.unusedRefreshing = true
      this.unusedPage = 1
      this.unusedHasMore = true
      this.unusedCoupons = []
      this.loadUnusedCoupons().then(() => {
        this.unusedRefreshing = false
      })
    },

    // 下拉刷新处理函数 - 已使用优惠券
    onUsedRefresh() {
      this.usedRefreshing = true
      this.usedPage = 1
      this.usedHasMore = true
      this.usedCoupons = []
      this.loadUsedCoupons().then(() => {
        this.usedRefreshing = false
      })
    },

    // 下拉刷新处理函数 - 已过期优惠券
    onExpiredRefresh() {
      this.expiredRefreshing = true
      this.expiredPage = 1
      this.expiredHasMore = true
      this.expiredCoupons = []
      this.loadExpiredCoupons().then(() => {
        this.expiredRefreshing = false
      })
    },

    // 加载当前标签页的数据
    loadCurrentTabData() {
      switch (this.currentTab) {
        case 0:
          this.loadUnusedCoupons()
          break
        case 1:
          this.loadUsedCoupons()
          break
        case 2:
          this.loadExpiredCoupons()
          break
      }
    },

    // 加载未使用优惠券
    async loadUnusedCoupons() {
      if (this.loading || this.unusedLoading || !this.unusedHasMore) return

      this.unusedLoading = true

      // 只在首次加载或下拉刷新时显示加载提示
      if (this.unusedPage === 1) {
        uni.showLoading({
          title: '加载中...'
        })
      }

      try {
        const res = await this.$get('coupon/mylist', {
          status: 0,
          page: this.unusedPage,
          limit: this.limit
        })

        if (res.errno === 0) {
          const newCoupons = res.data.list || []

          // 判断是否还有更多数据
          this.unusedHasMore = this.unusedPage < res.data.pages

          // 追加数据
          if (this.unusedPage === 1) {
            this.unusedCoupons = newCoupons
          } else {
            this.unusedCoupons = [...this.unusedCoupons, ...newCoupons]
          }
        } else {
          console.error('获取未使用优惠券失败：', res.errmsg)
          uni.showToast({
            title: res.errmsg || '获取优惠券失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取未使用优惠券失败', error)
        uni.showToast({
          title: '获取优惠券失败',
          icon: 'none'
        })
      } finally {
        this.unusedLoading = false
        if (this.unusedPage === 1) {
          uni.hideLoading()
        }
      }
    },

    // 加载已使用优惠券
    async loadUsedCoupons() {
      if (this.loading || this.usedLoading || !this.usedHasMore) return

      this.usedLoading = true

      // 只在首次加载或下拉刷新时显示加载提示
      if (this.usedPage === 1) {
        uni.showLoading({
          title: '加载中...'
        })
      }

      try {
        const res = await this.$get('coupon/mylist', {
          status: 1,
          page: this.usedPage,
          limit: this.limit
        })

        if (res.errno === 0) {
          const newCoupons = res.data.list || []
          // 判断是否还有更多数据
          this.usedHasMore = this.usedPage < res.data.pages

          // 追加数据
          if (this.usedPage === 1) {
            this.usedCoupons = newCoupons
          } else {
            this.usedCoupons = [...this.usedCoupons, ...newCoupons]
          }
        } else {
          console.error('获取已使用优惠券失败：', res.errmsg)
          uni.showToast({
            title: res.errmsg || '获取优惠券失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取已使用优惠券失败', error)
        uni.showToast({
          title: '获取优惠券失败',
          icon: 'none'
        })
      } finally {
        this.usedLoading = false
        if (this.usedPage === 1) {
          uni.hideLoading()
        }
      }
    },

    // 加载已过期优惠券
    async loadExpiredCoupons() {
      if (this.loading || this.expiredLoading || !this.expiredHasMore) return

      this.expiredLoading = true

      // 只在首次加载或下拉刷新时显示加载提示
      if (this.expiredPage === 1) {
        uni.showLoading({
          title: '加载中...'
        })
      }

      try {
        const res = await this.$get('coupon/mylist', {
          status: 2,
          page: this.expiredPage,
          limit: this.limit
        })

        if (res.errno === 0) {
          const newCoupons = res.data.list || []

          // 判断是否还有更多数据
          this.expiredHasMore = this.expiredPage < res.data.pages

          // 追加数据
          if (this.expiredPage === 1) {
            this.expiredCoupons = newCoupons
          } else {
            this.expiredCoupons = [...this.expiredCoupons, ...newCoupons]
          }
        } else {
          console.error('获取已过期优惠券失败：', res.errmsg)
          uni.showToast({
            title: res.errmsg || '获取优惠券失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取已过期优惠券失败', error)
        uni.showToast({
          title: '获取优惠券失败',
          icon: 'none'
        })
      } finally {
        this.expiredLoading = false
        if (this.expiredPage === 1) {
          uni.hideLoading()
        }
      }
    },

    // 加载更多未使用优惠券
    loadMoreUnused() {
      if (this.unusedHasMore && !this.unusedLoading) {
        this.unusedPage++
        this.loadUnusedCoupons()
      }
    },

    // 加载更多已使用优惠券
    loadMoreUsed() {
      if (this.usedHasMore && !this.usedLoading) {
        this.usedPage++
        this.loadUsedCoupons()
      }
    },

    // 加载更多已过期优惠券
    loadMoreExpired() {
      if (this.expiredHasMore && !this.expiredLoading) {
        this.expiredPage++
        this.loadExpiredCoupons()
      }
    },

    // 切换标签
    switchTab(index) {
      if (this.currentTab === index) return
      this.currentTab = index
      this.loadCurrentTabData()
    },

    // 滑动切换
    handleSwiperChange(e) {
      const index = e.detail.current
      if (this.currentTab === index) return
      this.currentTab = index

      // 如果该标签页还没有数据，则加载数据
      if (index === 0 || index === 1 || index === 2) {
        this.loadCurrentTabData()
      }
    },

    // 使用优惠券
    useCoupon(coupon) {
      // 根据优惠券类型跳转到不同的商品列表
      if (coupon.goodsType === 2) {
        // 指定商品类型，跳转到指定商品列表
        uni.navigateTo({
          url: '/pages/goods-list/index?couponId=' + coupon.cid
        })
      } else {
        // 全场通用类型，跳转到商品列表
        uni.switchTab({
          url: '/pages/category/index'
        })
      }
    },

    // 查看优惠券详情
    viewCouponDetail(coupon) {
      uni.navigateTo({
        url: `/pages/coupon/user-detail?id=${coupon.cid}&name=${encodeURIComponent(coupon.name)}&desc=${encodeURIComponent(coupon.desc)}&discount=${coupon.discount}&min=${coupon.min}&startTime=${encodeURIComponent(coupon.startTime)}&endTime=${encodeURIComponent(coupon.endTime)}&goodsType=${coupon.goodsType}&status=${this.currentTab}&tag=${encodeURIComponent(coupon.tag || '')}&days=${coupon.days || 0}`
      })
    },

    // 前往优惠券中心
    goToCouponCenter() {
      uni.navigateTo({
        url: '/pages/coupon/center'
      })
    },

    // 格式化金额
    formatAmount(amount) {
      return amount.toFixed(2)
    },

    // 格式化折扣
    formatDiscount(discount) {
      return (discount / 10).toFixed(1)
    },

    // 格式化日期
    formatDate(dateStr) {
      // 处理iOS兼容性问题，将yyyy-MM-dd HH:mm:ss格式转换为yyyy/MM/dd HH:mm:ss
      if (dateStr) {
        // 替换横杠为斜杠，确保iOS设备可以正确解析
        dateStr = dateStr.replace(/-/g, '/')
      }
      const date = new Date(dateStr)
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '日期无效'
      }
      return `${date.getMonth() + 1}.${date.getDate()}`
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/common/theme.scss';

.my-coupons {
  min-height: 100vh;
  background-color: $bg-main;
  display: flex;
  flex-direction: column;
}

.tabs {
  display: flex;
  background-color: #fff;
  padding: 0 30rpx;
  height: 100rpx;
  position: relative;
  z-index: 2;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);

  .tab-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28rpx;
    color: $primary-light-pink;
    position: relative;

    &.active {
      color: $primary-dark-pink;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 6rpx;
        background-color: $primary-pink;
        border-radius: 3rpx;
      }
    }
  }
}

.coupon-swiper {
  background-color: $bg-main;
  height: calc(100vh - 100rpx); /* 减去tabs的高度 */
}

.coupon-scroll {
  height: 100%;
  box-sizing: border-box;
}

.coupon-list {
  padding: 24rpx;

  .coupon-item {
    display: flex;
    margin-bottom: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    &.used {
      opacity: 0.8;

      .coupon-left {
        background-color: #999;
      }
    }

    &.expired {
      opacity: 0.6;

      .coupon-left {
        background-color: #999;
      }
    }

    .coupon-left {
      width: 220rpx;
      padding: 30rpx 20rpx;
      background-color: #b84a39;
      color: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 0;
        bottom: 0;
        width: 20rpx;
        background: radial-gradient(
          circle at left,
          transparent 10rpx,
          #fff 10rpx
        );
        background-size: 20rpx 20rpx;
        background-position: -10rpx 10rpx;
      }

      &.discount-coupon {
        background-color: #ff9500;
      }

      &.free-coupon {
        background-color: #5e35b1;
      }

      .coupon-tag {
        position: absolute;
        top: 0rpx;
        left: 0rpx;
        font-size: 16rpx;
        color: #fff;
        padding: 2rpx 6rpx;
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 4rpx;
      }

      .discount {
        display: flex;
        align-items: baseline;

        .amount {
          font-size: 40rpx;
          font-weight: bold;
        }

        .unit {
          font-size: 28rpx;
          margin-left: 4rpx;
        }
      }

      .condition {
        font-size: 24rpx;
        margin-top: 10rpx;
        opacity: 0.9;
      }
    }

    .coupon-right {
      flex: 1;
      padding: 20rpx 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: relative;

      .coupon-info {
        flex: 1;

        .coupon-name {
          font-size: 30rpx;
          font-weight: bold;
          color: $primary-dark-pink;
          margin-bottom: 10rpx;
        }

        .coupon-desc {
          font-size: 24rpx;
          color: $primary-light-pink;
          margin-bottom: 10rpx;
        }

        .coupon-time {
          font-size: 22rpx;
          color: #999;
        }
      }

      .coupon-action {
        width: 140rpx;

        .use-btn {
          width: 100%;
          height: 60rpx;
          line-height: 60rpx;
          font-size: 24rpx;
          color: #fff;
          background-color: $gradient-button;
          border-radius: 30rpx;
          padding: 0;
        }
      }

      .status-mark {
        position: absolute;
        right: 30rpx;
        top: 20rpx;
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .empty-tip {
    padding: 100rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;

    .empty-icon {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 20rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999;
      margin-bottom: 30rpx;
    }

    .go-center-btn {
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 28rpx;
      color: #fff;
      background-color: $gradient-button;
      border-radius: 40rpx;
    }
  }
}

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}
</style>
